package com.gzhryc.shared_device.oem.code.agent.services;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.oem.code.agent.dao.AgentDao;
import com.gzhryc.shared_device.oem.code.agent.dao.db.Agent;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentSearch;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class AgentService {

    static Logger log = Logger.getLogger(AgentService.class);

    public static AgentService self() {
        return MultiDBTools.getService(AgentService.class, true);
    }

    public static AgentService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, AgentService.class, true);
    }

    AgentDao dao;

    public AgentService(String jdbcKey) {
        this.dao = new AgentDao(jdbcKey);
    }

    public List<Agent> findJoinBySearch(AgentSearch search,Integer pageNo,Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().likeBoth("user.nickname",search.getTrim()).or()
                .likeBoth("user.name",search.getTrim()).or().likeBoth("user.phone",search.getTrim());
        conditions.and().likeBoth("user.name",search.getName());
        conditions.and().likeBoth("user.phone",search.getPhone());
        conditions.desc("createDate");
        try {
            return dao.findJoinByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public List<Agent> findByUserIds(List<Long> userIds){
        if(userIds != null && userIds.size() > 0){
            Conditions conditions = new Conditions(Agent.class);
            conditions.and().in("userId",userIds);

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public List<Agent> findJoinByUserIds(List<Long> userIds){
        if(userIds != null && userIds.size() > 0){
            Conditions conditions = new Conditions(Agent.class);
            conditions.and().in("userId",userIds);

            try {
                return dao.findJoinByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public Long countJoinBySearch(AgentSearch search){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().likeBoth("user.nickname",search.getTrim()).or()
                .likeBoth("user.name",search.getTrim()).or().likeBoth("user.phone",search.getTrim());
        conditions.and().likeBoth("user.name",search.getName());
        conditions.and().likeBoth("user.phone",search.getPhone());
        try {
            return dao.countJoin(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Agent getByUserId(Long userId){
        try {
            return dao.getById(userId);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Agent getJoinByUserId(Long userId){
        try {
            return dao.getJoinById(userId);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }
    
    public boolean replaceLastLogin(Long userId) {
    	if(userId != null) {
	    	Agent updateEntity = new Agent();
	    	updateEntity.setUserId(userId);
	    	updateEntity.setLastLoginDate(new Date());
	    	 try {
	             return dao.updateNotNull(updateEntity) > 0;
	         } catch (SQLException e) {
	             log.error(e.getMessage(),e);
	         }
    	}
    	return false;
    }

    public boolean add(Agent agent, User user) throws LogicException {
        if(StringTools.isNotBlank(user.getPhone()) && agent.getServiceChargeRatio() != null){
            User temp = UserService.self().getByPhone(user.getPhone());
            if(temp == null){
                JdbcSession.begin();
                try {
                    if(UserService.self().add(user)) {
                        agent.setUserId(user.getId());
                        agent.setCreateDate(new Date());
                        if (dao.insert(agent) > 0) {
                            JdbcSession.commit();
                            return true;
                        }
                    }
                } catch (SQLException e) {
                    log.error(e.getMessage(),e);
                } finally {
                    JdbcSession.end();
                }
            }else {
                agent.setUserId(temp.getId());
                agent.setCreateDate(new Date());
                try {
                    if(dao.insert(agent) > 0){
                        return true;
                    }
                } catch (SQLException e) {
                    log.error(e.getMessage(),e);
                }
            }
        }
        return false;
    }

    public boolean updateServiceChargeRatio(Long userId,Double serviceChargeRatio) throws LogicException{
        if(userId != null && serviceChargeRatio != null){
            Agent agent = new Agent();
            agent.setUserId(userId);
            agent.setServiceChargeRatio(serviceChargeRatio);

            try {
                return dao.updateNotNull(agent) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean updateLevel(Long userId,Integer level) throws LogicException{
        if(userId != null && level != null){
            Agent agent = new Agent();
            agent.setUserId(userId);
            agent.setLevel(level);

            try {
                return dao.updateNotNull(agent) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }
    
    public boolean updateServiceChargeRatioByLevel(Integer level,Double serviceChargeRatio) throws LogicException{
        if(level != null){
        	Conditions condition = new Conditions(Agent.class);
        	condition.and().is("level", level);
        	
            Agent agent = new Agent();
            agent.setServiceChargeRatio(serviceChargeRatio);

            try {
                return dao.updateNotNull(agent,condition) >= 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }
    
    public boolean updateServiceChargeRatioByLevel2(Integer level,Double serviceChargeRatio) throws LogicException{
        if(level != null){
        	Conditions condition = new Conditions(Agent.class);
        	condition.and().is("level", level);
        	condition.and().gt("serviceChargeRatio", serviceChargeRatio);
        	
            Agent agent = new Agent();
            agent.setServiceChargeRatio(serviceChargeRatio);

            try {
                return dao.updateNotNull(agent,condition) >= 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }
    
    public boolean updateServiceChargeRatioByLevel3(Integer level,Double serviceChargeRatio) throws LogicException{
        if(level != null){
        	Conditions condition = new Conditions(Agent.class);
        	condition.and().is("level", level);
        	condition.and().lt("serviceChargeRatio", serviceChargeRatio);
        
            Agent agent = new Agent();
            agent.setServiceChargeRatio(serviceChargeRatio);

            try {
                return dao.updateNotNull(agent,condition) >= 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean deleteById(Long userId) throws LogicException{
        JdbcSession.begin();
        try {
            if(dao.deleteById(userId) > 0){
                if(AgentRelationService.self().faceDeleteByRelationUserId(userId)) {
                    if(AgentRelationService.self().faceDeleteByUserId(userId)) {
                        JdbcSession.commit();
                        return true;
                    }
                }
            }
        } catch (SQLException e) {
           log.error(e.getMessage(),e);
        }finally {
            JdbcSession.end();
        }
        return false;
    }
}
